using System;
using System.Data;
using System.Configuration;
using Pheonix.Fashionzoomer.DAL;
using System.Data.SqlClient;
using System.Collections;
using Pheonix.CodeLibrary.Data;
using Pheonix.CodeLibrary;

/// <summary>
/// Summary description for Article
/// </summary>

namespace Pheonix.Fashionzoomer.Entity.SqlServer2000
{
    [System.ComponentModel.DataObject]
    public class Article : SqlServerDAO
    {
        #region Article Private Fields

		private Int32 _id;
		private String _articleTitle;
		private String _articleText;
		private Decimal _rating;
		private Int32 _totalRater;
		private Int32 _totalView;
		private String _imagePath;
		private Int32 _revieweId;
		private DateTime _createdOn;
		private DateTime _lastUpdate;
		private String _keywords;

        #endregion

        #region Article Constractors

		public Article(){}

		public Article
		(
			Int32 id,
			String articleTitle,
			String articleText,
			Decimal rating,
			Int32 totalRater,
			Int32 totalView,
			String imagePath,
			Int32 revieweId,
			DateTime createdOn,
			DateTime lastUpdate,
			String keywords

		)
		{
			this._id = id;
			this._articleTitle = articleTitle;
			this._articleText = articleText;
			this._rating = rating;
			this._totalRater = totalRater;
			this._totalView = totalView;
			this._imagePath = imagePath;
			this._revieweId = revieweId;
			this._createdOn = createdOn;
			this._lastUpdate = lastUpdate;
			this._keywords = keywords;
		}

        #endregion

        #region Article Properties

		public Int32 Id
		{
			get{ return this._id; }
			set{ this._id = value; }
		}

		public String ArticleTitle
		{
			get{ return this._articleTitle; }
			set{ this._articleTitle = value; }
		}

		public String ArticleText
		{
			get{ return this._articleText; }
			set{ this._articleText = value; }
		}

		public Decimal Rating
		{
			get{ return this._rating; }
			set{ this._rating = value; }
		}

		public Int32 TotalRater
		{
			get{ return this._totalRater; }
			set{ this._totalRater = value; }
		}

		public Int32 TotalView
		{
			get{ return this._totalView; }
			set{ this._totalView = value; }
		}

		public String ImagePath
		{
			get{ return this._imagePath; }
			set{ this._imagePath = value; }
		}

		public Int32 RevieweId
		{
			get{ return this._revieweId; }
			set{ this._revieweId = value; }
		}

		public DateTime CreatedOn
		{
			get{ return this._createdOn; }
			set{ this._createdOn = value; }
		}

		public DateTime LastUpdate
		{
			get{ return this._lastUpdate; }
			set{ this._lastUpdate = value; }
		}

		public String Keywords
		{
			get{ return this._keywords; }
			set{ this._keywords = value; }
		}


        #endregion

        #region Article Static Methods

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Insert, true)]
        public static Int32 CreateNewArticle
        (
			String articleTitle,
			String articleText,
			Decimal rating,
			Int32 totalRater,
			Int32 totalView,
			String imagePath,
			Int32 revieweId,
			DateTime createdOn,
			DateTime lastUpdate,
			String keywords

        )
        {
            //creating an empty Article object
            Article article = new Article();
            article.ArticleTitle = articleTitle;
			article.ArticleText = articleText;
			article.Rating = rating;
			article.TotalRater = totalRater;
			article.TotalView = totalView;
			article.ImagePath = imagePath;
			article.RevieweId = revieweId;
			article.CreatedOn = createdOn;
			article.LastUpdate = lastUpdate;
			article.Keywords = keywords;

            return Article.CreateNewArticle(article);
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static bool UpdateArticle
        (
			Int32 id,
			String articleTitle,
			String articleText,
			Decimal rating,
			Int32 totalRater,
			Int32 totalView,
			String imagePath,
			Int32 revieweId,
			DateTime createdOn,
			DateTime lastUpdate,
			String keywords

        )
        {
            Article article = Article.GetArticleById(id);
            article.ArticleTitle = articleTitle;
			article.ArticleText = articleText;
			article.Rating = rating;
			article.TotalRater = totalRater;
			article.TotalView = totalView;
			article.ImagePath = imagePath;
			article.RevieweId = revieweId;
			article.CreatedOn = createdOn;
			article.LastUpdate = lastUpdate;
			article.Keywords = keywords;

            return Article.UpdateArticle(article);
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static bool DeleteArticle
        (
            Int32 id
        )
        {
            //Validate Input
            if (id <= GetIdMinValue)
                throw (new ArgumentOutOfRangeException("id in Article"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddParameterToSqlCmd(sqlCmd, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, id);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_ARTICLE_DELETEARTICLE);
            GetOneData(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == 0 ? false : true);

        }

        public static bool DeleteArticleList(System.Collections.Generic.List<Int32> idListToDelete)
        {
            //Validate Input
            foreach (Int32 id in idListToDelete)
                if (id <= GetIdMinValue)
                    throw (new ArgumentOutOfRangeException("id in Article"));

            //performing deletion operation //

            string csvString = Utility.MakeCSV(idListToDelete);

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddParameterToSqlCmd(sqlCmd, "@IdList", SqlDbType.NVarChar, csvString.Length, 
                ParameterDirection.Input, csvString);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_ARTICLE_DELETEARTICLELIST);
            GetOneData(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == idListToDelete.Count ? true : false);
        }
		
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
		public static CustomCollection<Article> GetArticleByRevieweId(Int32 revieweId)
		{
			if(revieweId <= GetIdMinValue)
				throw (new ArgumentOutOfRangeException("revieweId in Article"));

			SqlCommand sqlCmd = new SqlCommand();
			AddParameterToSqlCmd(sqlCmd, "@RevieweId", SqlDbType.Int, 0, ParameterDirection.Input, revieweId);
			SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_ARTICLE_GETARTICLEBYREVIEWEID);
			GenerateCollectionFromReader dg = new GenerateCollectionFromReader(GenerateArticleCollectionFromReader);
			CustomCollection<Article> objCollection = ((CustomCollection<Article>)GetAllData(sqlCmd, dg));

			if (objCollection.Count > 0)
				return objCollection;
			else
				return null;
		}

        #endregion

        #region Article Instance Methods
        
        public bool Save()
		{
			if(Id <= GetIdMinValue)
			{
				Int32 TempId=CreateNewArticle(this);
				if(TempId>0)
				{
					_id=TempId;
					return true;
				}
				else
				{
					// error occurs
					return false;
				}
			}
			else
			{	//This is a update Command
				return (UpdateArticle(this));
			}
		}

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static CustomCollection<Article> GetAllArticle()
        {
            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_ARTICLE_GETALLARTICLE);
            GenerateCollectionFromReader result = new GenerateCollectionFromReader(GenerateArticleCollectionFromReader);
            CustomCollection<Article> objCollection = ((CustomCollection<Article>)GetAllData(sqlCmd, result));

            return objCollection;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static CustomCollection<Article> GetAllArticlePaged(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            //Validate Input
            if (orderBy == "")
                orderBy = "Id";

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@orderby", SqlDbType.VarChar, 50, ParameterDirection.Input, orderBy);
            AddParameterToSqlCmd(sqlCmd, "@startRowIndex", SqlDbType.Int, 0, ParameterDirection.Input, startRowIndex);
            AddParameterToSqlCmd(sqlCmd, "@maximumRows", SqlDbType.Int, 0, ParameterDirection.Input, maximumRows);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_ARTICLE_GETALLARTICLEPAGED);

            GenerateCollectionFromReader result = new GenerateCollectionFromReader(GenerateArticleCollectionFromReader);
            CustomCollection<Article> objCollection = ((CustomCollection<Article>)GetAllData(sqlCmd, result));
            return objCollection;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static int GetAllArticlePagedCount(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();

            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_ARTICLE_GETALLARTICLEPAGEDCOUNT);
            GetOneData(sqlCmd);

            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return returnValue;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static Article GetArticleById(Int32 id)
        {
            if (id <= GetIdMinValue)
                throw (new ArgumentOutOfRangeException("id in Article"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, id);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_ARTICLE_GETARTICLEBYID);
            GenerateCollectionFromReader result = new GenerateCollectionFromReader(GenerateArticleCollectionFromReader);
            CustomCollection<Article> objCollection = ((CustomCollection<Article>)GetAllData(sqlCmd, result));

            if (objCollection.Count > 0)
                return (Article)objCollection[0];
            else
                return null;
        }

        public static Int32 CreateNewArticle(Article newArticle)
        {
            // validate Parameters
            if (newArticle == null)
                throw (new ArgumentNullException("newArticle in Article"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);

            AddParameterToSqlCmd(sqlCmd, "@ArticleTitle", SqlDbType.NVarChar, 512, ParameterDirection.Input, newArticle.ArticleTitle);
			AddParameterToSqlCmd(sqlCmd, "@ArticleText", SqlDbType.NText, 0, ParameterDirection.Input, newArticle.ArticleText);
			AddParameterToSqlCmd(sqlCmd, "@Rating", SqlDbType.Decimal, 0, ParameterDirection.Input, newArticle.Rating);
			AddParameterToSqlCmd(sqlCmd, "@TotalRater", SqlDbType.Int, 0, ParameterDirection.Input, newArticle.TotalRater);
			AddParameterToSqlCmd(sqlCmd, "@TotalView", SqlDbType.Int, 0, ParameterDirection.Input, newArticle.TotalView);
			AddParameterToSqlCmd(sqlCmd, "@ImagePath", SqlDbType.NVarChar, 128, ParameterDirection.Input, newArticle.ImagePath);
			AddParameterToSqlCmd(sqlCmd, "@RevieweId", SqlDbType.Int, 0, ParameterDirection.Input, newArticle.RevieweId);
			AddParameterToSqlCmd(sqlCmd, "@CreatedOn", SqlDbType.DateTime, 0, ParameterDirection.Input, newArticle.CreatedOn);
			AddParameterToSqlCmd(sqlCmd, "@LastUpdate", SqlDbType.DateTime, 0, ParameterDirection.Input, newArticle.LastUpdate);
			AddParameterToSqlCmd(sqlCmd, "@Keywords", SqlDbType.NVarChar, 512, ParameterDirection.Input, newArticle.Keywords);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_ARTICLE_CREATENEWARTICLE);
            GetOneData(sqlCmd);
            return ((Int32)sqlCmd.Parameters["@ReturnValue"].Value);

        }

        public static bool UpdateArticle(Article newArticle)
        {
            // validate Parameters
            if (newArticle == null)
                throw (new ArgumentNullException("newArticle"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);

            AddParameterToSqlCmd(sqlCmd, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, newArticle.Id);
            AddParameterToSqlCmd(sqlCmd, "@ArticleTitle", SqlDbType.NVarChar, 512, ParameterDirection.Input, newArticle.ArticleTitle);
			AddParameterToSqlCmd(sqlCmd, "@ArticleText", SqlDbType.NText, 0, ParameterDirection.Input, newArticle.ArticleText);
			AddParameterToSqlCmd(sqlCmd, "@Rating", SqlDbType.Decimal, 0, ParameterDirection.Input, newArticle.Rating);
			AddParameterToSqlCmd(sqlCmd, "@TotalRater", SqlDbType.Int, 0, ParameterDirection.Input, newArticle.TotalRater);
			AddParameterToSqlCmd(sqlCmd, "@TotalView", SqlDbType.Int, 0, ParameterDirection.Input, newArticle.TotalView);
			AddParameterToSqlCmd(sqlCmd, "@ImagePath", SqlDbType.NVarChar, 128, ParameterDirection.Input, newArticle.ImagePath);
			AddParameterToSqlCmd(sqlCmd, "@RevieweId", SqlDbType.Int, 0, ParameterDirection.Input, newArticle.RevieweId);
			AddParameterToSqlCmd(sqlCmd, "@CreatedOn", SqlDbType.DateTime, 0, ParameterDirection.Input, newArticle.CreatedOn);
			AddParameterToSqlCmd(sqlCmd, "@LastUpdate", SqlDbType.DateTime, 0, ParameterDirection.Input, newArticle.LastUpdate);
			AddParameterToSqlCmd(sqlCmd, "@Keywords", SqlDbType.NVarChar, 512, ParameterDirection.Input, newArticle.Keywords);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_ARTICLE_UPDATEARTICLE);
            GetOneData(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == 0 ? false : true);
        }

        #endregion

        #region Article Related Collections
        /// <summary>
        /// Creates and returns a strongly typed collection of Article custom entity. 
        /// The colelction is created through iterating on the IdataReader object which contains 
        /// Article information, as a set of records, similar to tabular format.
        /// </summary>
        public static IList GenerateArticleCollectionFromReader(IDataReader returnData)
        {

            //creating the instance of Article collection
            CustomCollection<Article> colArticle = new CustomCollection<Article>();

            //Iterating thriugh the data reader, to generate Article collection.

            //getting the Article collection by iterating thru the data reader
            while (returnData.Read())
            {
                //passing the Article constructor parameters from the current instance of data reader fields.
                Article newArticle = new Article
                (
                    returnData["id"] == System.DBNull.Value ? GetIdMinValue : (Int32)returnData["id"],
                    returnData["article_title"] == System.DBNull.Value ? String.Empty : (String)returnData["article_title"],
					returnData["article_text"] == System.DBNull.Value ? String.Empty : (String)returnData["article_text"],
					returnData["rating"] == System.DBNull.Value ? Decimal.MinValue : (Decimal)returnData["rating"],
					returnData["total_rater"] == System.DBNull.Value ? Int32.MinValue : (Int32)returnData["total_rater"],
					returnData["total_view"] == System.DBNull.Value ? Int32.MinValue : (Int32)returnData["total_view"],
					returnData["image_path"] == System.DBNull.Value ? String.Empty : (String)returnData["image_path"],
					returnData["reviewe_id"] == System.DBNull.Value ? Int32.MinValue : (Int32)returnData["reviewe_id"],
					returnData["created_on"] == System.DBNull.Value ? DateTime.MinValue : (DateTime)returnData["created_on"],
					returnData["last_update"] == System.DBNull.Value ? DateTime.MinValue : (DateTime)returnData["last_update"],
					returnData["keywords"] == System.DBNull.Value ? String.Empty : (String)returnData["keywords"]

                );
                //adding the Article to the collection
                colArticle.Add(newArticle);
            }

            //returns the collection of Article 
            return (colArticle);
        }

        #endregion

        #region Constants and Default Values

        public static Int32 GetIdMinValue
        {
            get
            {
                return 0;
            }
        }

        //contants
        internal const string SPR_ARTICLE_CREATENEWARTICLE = "spr_Article_CreateNewArticle";
        internal const string SPR_ARTICLE_UPDATEARTICLE = "spr_Article_UpdateArticle";
        internal const string SPR_ARTICLE_DELETEARTICLE = "spr_Article_DeleteArticle";
        internal const string SPR_ARTICLE_DELETEARTICLELIST = "spr_Article_DeleteArticleList";
        internal const string SPR_ARTICLE_GETARTICLEBYID = "spr_Article_GetArticleById";
        internal const string SPR_ARTICLE_GETALLARTICLE = "spr_Article_GetAllArticle";
        internal const string SPR_ARTICLE_GETALLARTICLEPAGED = "spr_Article_GetAllArticlePaged";
        internal const string SPR_ARTICLE_GETALLARTICLEPAGEDCOUNT = "spr_Article_GetAllArticlePagedCount";

		//Foreign key contants
		internal const string SPR_ARTICLE_GETARTICLEBYREVIEWEID="spr_Article_GetArticleByRevieweId";
		internal const string SPR_ARTICLE_GETARTICLEBYREVIEWEIDPAGED="spr_Article_GetArticleByRevieweIdPaged";
		internal const string SPR_ARTICLE_GETARTICLEBYREVIEWEIDPAGEDCOUNT="spr_Article_GetArticleByRevieweIdPagedCount";
		
        #endregion
    }
}
